<?php

namespace app\common\model;

use think\Model;

class UrlsModel extends Model
{
    private $len = '9';//短码长度9
    private $expire_time = 60*60*24*365;//一年
    /**
     * 数据表名称
     * @var string
     */
    protected $table = 'urls';

    /**短码
     * @param $short_code
     */
    public function findByShortcode($short_code){
        return $this->where(array('short_code'=>$short_code))->find();
    }

    /**创建短网址
     * @param string $code 短码
     */
    public function createUrl($origin_url,$short_code = '',$user_id='',$expire_time=''){
        $expire_time = empty($expire_time)?$this->expire_time:$expire_time;
        if(!empty($short_code)){
            if($this->findByShortcode($short_code)){
                return array('error'=>1,'msg'=>'短码已经被占用');
            }
        }else{
            $short_code = $this->getCode();
        }
        $urlData =array(
            'user_id'=>$user_id,
            'short_code'=>$short_code,
            'origin_url'=>$origin_url,
            'expire_time'=>$expire_time,
        );
        if($this->save($urlData)){
            return array('error'=>0,'msg'=>'保存成功');
        }
        return array('error'=>1,'msg'=>'短码保存失败');
    }

    /**获取唯一短码
     * @return string
     */
    public function getCode(){
        $code = randStr($this->len);
        if($this->findByShortcode( $code)){
            $this->getCode();
        }
        return $code;
    }
}
